﻿using System;
using System.Data.Common;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;

namespace QDCommon.DB{
    public class DBManager<T> where T:DbConnection
    {
        public string ConnectionStr { get; set; }
        public DBManager(string connectionStr)
        {
            ConnectionStr = connectionStr;
        }

        public virtual  T Connection()
        {
            return null;
        }
        public async Task Query(Func<T,Task> action) 
        {
           
            try
            {
                using (T con = Connection())
                {
                    await con.OpenAsync();
                    if(action!=null)
                    {
                        await action(con);
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        
        }

        public async Task WithTransform(Action<T,DbTransaction> action)
        {
            try
            {
                using (T con = Connection())
                {
                    await con.OpenAsync();
                    using (var transform = con.BeginTransaction())
                    {
                        try{

                            action?.Invoke(con,transform);
                        }
                        catch(Exception ex)
                        {
                            Console.Write(ex.Message);
                            transform.Rollback();
                        }

                    }
                   
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
    }
}